<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧商户树 -->
      <el-col :span="5" :xs="24">
        <merchant-tree @node-click="handleMerchantNodeClick" ref="merchantTreeRef" />
      </el-col>
      
      <!-- 右侧客户列表 -->
      <el-col :span="19" :xs="24">
        <el-card class="common-card query-box">
          <div class="queryForm">
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
              <el-form-item label="客户名称">
                <el-input v-model="queryParams.customerName" placeholder="请输入客户名称"/>
              </el-form-item>
              <el-form-item label="客户类型">
                <el-select style="width: 240px" v-model="queryParams.customerType" clearable placeholder="请选择">
                  <el-option label="个人" value="个人"/>
                  <el-option label="企业" value="企业"/>
                </el-select>
              </el-form-item>
              <el-form-item label="负责人">
                <el-input v-model="queryParams.customerHead" placeholder="请输入负责人"/>
              </el-form-item>
              <el-form-item label="客户分组">
                <el-select style="width: 240px" v-model="queryParams.segmentId" clearable placeholder="请选择">
                  <el-option v-for="(item, index) in dataSegmentList" :key="index"
                            :value="item.id" :label="item.segmentName"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">{{ t('org.button.query') }}</el-button>
                <el-button @click="resetQuery">{{ t('org.button.reset') }}</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>

        <el-card class="common-card">
          <div class="btn-form">
            <el-button type="primary" @click="handleAdd">{{ $t('jbx.text.add') }}</el-button>
            <el-button @click="onBatchDelete" :disabled="ids.length === 0">{{ $t('jbx.text.deleteBatch') }}</el-button>
          </div>
          <el-table v-loading="loading" :data="dataList" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column label="跟进" align="center" width="60"
                            :show-overflow-tooltip="true">
              <template #default="scope">
                <el-button icon="Comment" type="warning" link @click="followUp(scope.row)"></el-button>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="联系电话" align="center" width="120"></el-table-column>
            <el-table-column prop="customerName" label="客户名称" align="left" header-align="center" ></el-table-column>
            <el-table-column prop="customerType" label="客户类型" align="center"  width="80"></el-table-column>
            <el-table-column prop="segmentName" label="所在分层" align="center"  width="120">
              <template #default="scope">
                <el-tag type="info" v-if="scope.row.segmentId" effect="plain">
                  <text  :style="{color: getSegmentColor(scope.row.segmentId)}">
                    {{ scope.row.segmentName }}
                  </text>
                </el-tag>

              </template>
            </el-table-column>
            <el-table-column prop="industry" label="所属行业" align="center"></el-table-column>
            <el-table-column prop="customerFrom" label="来源渠道" align="center">
              <template #default="scope">
                {{ getChannelName(scope.row.customerFrom) }}
              </template>
            </el-table-column>
            <el-table-column prop="merchantCode" label="来源商户" align="center">
              <template #default="scope">
                {{ getMerchantName(scope.row.merchantCode) }}
              </template>
            </el-table-column>
            <el-table-column prop="customerHead" label="负责人" align="center"  width="120"></el-table-column>
            <el-table-column label="操作" align="center" width="140">
              <template #default="scope">
                <el-button icon="View" link @click="handleShow(scope.row)"></el-button>
                <el-button icon="Edit" link @click="handleUpdate(scope.row)"></el-button>
                <el-button icon="Delete" link @click="handleDelete(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNumber"
              v-model:limit="queryParams.pageSize"
              :page-sizes="queryParams.pageSizeOptions"
              @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑抽屉 -->
    <edit-form
        :title="title"
        :open="open"
        :form-id="id"
        @dialogOfClosedMethods="dialogOfClosedMethods"
    ></edit-form>
    
    <!-- 查看详情抽屉 -->
    <customer-detail 
      v-if="detailVisible"
      :title="detailTitle" 
      :open="detailOpen" 
      :customer-id="detailId"
      @update:open="onDetailClose"
    />
    
    <!-- 跟进-->
    <follow-up-form :relation-id="id" :open="followUpOpen" :title="title"
                    :follow-up-type="2"
                    @dialogOfClosedMethods="dialogOfClosedMethods">
    </follow-up-form>
  </div>
</template>

<script setup lang="ts">
import {getCurrentInstance, reactive, ref, toRefs, computed} from 'vue'
import {useI18n} from 'vue-i18n'
import {listCustomer, delCustomer} from '@/api/customer/customer'
import {listCustomerSegment} from '@/api/customer/customer-segment'
import {listMerchant} from '@/api/merchant/merchant'
import modal from '@/plugins/modal'
import editForm from './edit.vue'
import CustomerDetail from './detail.vue'
import {useRouter} from "vue-router";
import FollowUpForm from "@/views/follow-up/edit.vue";
import MerchantTree from './merchant-tree.vue'

const {t} = useI18n()
const router = useRouter()
const data: any = reactive({
  queryParams: {
    pageNumber: 1,
    pageSize: 10,
    pageSizeOptions: [10, 20, 50],
    customerName: '',
    customerType: '',
    customerHead: '',
    segmentId: '',
    merchantCode: undefined // 将merchantId改为merchantCode
  },
  form: {}
})

interface SegmentModel {
  id: string
  segmentName: string,
  colorCode: string
}

const dataList = ref([])
const dataSegmentList = ref<Array<SegmentModel>>([])
const dataSegmentMap = ref<Map<String, SegmentModel>>(new Map())
const merchants = ref([]) // 存储商户列表
const loading = ref(true)
const id = ref<string | undefined>()
const total = ref(0)
const title = ref('')
const open = ref(false)
const followUpOpen = ref(false);
const ids = ref<string[]>([])
const selectionlist = ref<any[]>([])
const {proxy} = getCurrentInstance()!;
const {queryParams, form} = toRefs(data)
const tableSelectDialog = ref()
const merchantTreeRef = ref()

// 客户详情相关变量
const detailOpen = ref(false)
const detailTitle = ref('')
const detailId = ref('')
const detailVisible = ref(true)

// 获取客户列表
function getList() {
  loading.value = true;
  listCustomer(queryParams.value).then((response: any) => {
    // 根据实际API返回结构处理数据
    if (response.data.records && response.data.total) {
      // 如果是分页结构
      dataList.value = response.data.records
      total.value = response.data.total
    } else if (Array.isArray(response.data)) {
      // 如果是直接数组结构
      dataList.value = response.data
      total.value = response.data.length
    } else {
      // 其他情况使用空数组
      dataList.value = []
      total.value = 0
    }
    loading.value = false
  }).catch(() => {
    // 添加错误处理
    dataList.value = []
    total.value = 0
    loading.value = false
  })
}

// 获取商户列表
function getMerchants() {
  listMerchant({}).then((res: any) => {
    merchants.value = res.data.records || res.data
  }).catch(() => {
    // 使用默认数据
    merchants.value = [
      { id: "1", merchantName: "自平台", merchantCode: "SELF" },
      { id: "2", merchantName: "示例商户2", merchantCode: "MERCHANT_2" }
    ]
  })
}

// 根据商户编码获取商户名称
function getMerchantName(merchantCode: string) {
  if (!merchantCode) return ''
  const merchant = merchants.value.find((item: any) => item.merchantCode === merchantCode)
  return merchant ? merchant.merchantName : merchantCode
}

// 根据渠道编码获取渠道名称（这里暂时直接显示编码，实际应通过接口获取渠道数据）
function getChannelName(channelCode: string) {
  // TODO: 实际应通过接口获取渠道数据
  return channelCode || ''
}

// 获取客户分组列表
function getSegmentList() {
  listCustomerSegment({
    pageNumber: 1,
    pageSize: 10000,
  }).then((response: any) => {
    dataSegmentList.value = response.data.records
    
    // 构建分组Map，便于通过ID获取颜色
    dataSegmentMap.value.clear()
    response.data.records.forEach((item: SegmentModel) => {
      dataSegmentMap.value.set(item.id, item)
    })
  }).catch(() => {
    // 错误处理
    console.error("获取客户分组列表失败");
  })
}

function getSegmentColor(segmentId: string) {
  const segment = dataSegmentMap.value.get(segmentId)
  return segment ? segment.colorCode : '#909399'
}

function handleQuery() {
  queryParams.value.pageNumber = 1
  getList()
}

function resetQuery() {
  queryParams.value.customerName = ''
  queryParams.value.customerType = ''
  queryParams.value.customerHead = ''
  queryParams.value.segmentId = ''
  // 保留商户筛选条件
  const merchantCode = queryParams.value.merchantCode;
  queryParams.value.merchantCode = merchantCode;
  handleQuery()
}

function handleSelectionChange(selection: any) {
  selectionlist.value = selection
  ids.value = selectionlist.value.map((item: any) => item.id)
}

function handleAdd() {
  id.value = undefined
  title.value = t('jbx.text.add')
  open.value = true
}

function handleUpdate(row: any) {
  id.value = row.id
  title.value = t('jbx.text.update')
  open.value = true
}

function handleShow(row: any) {
  // 使用抽屉展示客户详情
  detailId.value = row.id
  detailTitle.value = '客户详情'
  detailOpen.value = true
}

function handleDelete(row: any) {
  modal.confirm(t('org.deleteTip1') + row.customerName + t('org.deleteTip2')).then(function () {
    return delCustomer([row.id]);
  }).then(() => {
    getList()
    modal.msgSuccess(t('jbx.alert.delete.success'))
  }).catch(() => {
  })
}

function onBatchDelete() {
  modal.confirm(t('org.deleteTip1') + ids.value + t('org.deleteTip2')).then(function () {
    return delCustomer(ids.value);
  }).then(() => {
    getList()
    modal.msgSuccess(t('jbx.alert.delete.success'))
  }).catch(() => {
  })
}

function dialogOfClosedMethods(val: boolean) {
  open.value = false
  followUpOpen.value = false
  if (val) {
    getList()
  }
}

function followUp(row: any) {
  id.value = row.id
  title.value = "新增跟进"
  followUpOpen.value = true
}

// 处理商户节点点击事件
function handleMerchantNodeClick(data: any) {
  // 如果点击的是"全部"节点，则清空merchantCode筛选条件
  if (data.id === "0") {
    queryParams.value.merchantCode = undefined;
  } else {
    // 否则设置merchantCode为选中商户的merchantCode
    queryParams.value.merchantCode = data.merchantCode;
  }
  // 重置页码并重新查询
  queryParams.value.pageNumber = 1;
  getList();
}

// 处理详情抽屉关闭事件
function onDetailClose(val: boolean) {
  detailOpen.value = val
  detailVisible.value = false
  // 在下一个tick重新设置visible为true，确保组件可以正确重新渲染
  setTimeout(() => {
    detailVisible.value = true
  }, 0)
}

getList()
getSegmentList()
getMerchants()
</script>